<template>
	<div class="graywater-check-page">
		<div class="page-title">中水回用设施点检</div>

		<div class="main-form">
			<div class="title-panel">设施运行</div>
			<FormItemRadio label="运行状态" item-key="state" :required="true" v-model="form.state" :dic-key="'ZQT_SSZCYC'" :readonly="isView" />
			<FormItemRadio
				v-if="form.state === '0'"
				label="异常类型"
				item-key="exceptionType"
				:required="true"
				v-model="form.exceptionType"
				:dic-key="'ZQT_FSFQYCLX'"
			/>
			<van-field
				v-if="form.state === '0'"
				label="异常描述"
				:required="true"
				type="textarea"
				autosize
				v-model="form.exceptionDesc"
				placeholder="请输入"
			/>

			<FormItemDateTime
				:required="true"
				label="点检开始时间"
				v-model="form.beginTime"
				precision="minute"
				:min-date="minDate"
				:max-date="maxDate"
				:readonly="isView"
			/>
			<FormItemDateTime
				:required="true"
				label="点检结束时间"
				v-model="form.endTime"
				precision="minute"
				:min-date="minDate"
				:max-date="maxDate"
				:readonly="isView"
			/>

			<div class="title-panel">运行数据</div>
			<van-field v-model.number="form.inflow" label="进水量(m³)" type="number" placeholder="请输入" :readonly="isView" />
			<van-field v-model.number="form.produce" label="产水量(m³)" type="number" placeholder="请输入" :readonly="isView" />
			<van-field v-model.number="form.bottom" label="污泥量(kg)" type="number" placeholder="请输入" :readonly="isView" />

			<FormFileUpload v-model="form.fileData" :business-id="form.id" big-type="ZQT_ZSDJFJ" small-type="FJ" :readonly="isView" />
		</div>

		<div style="margin: 16px" v-if="!isView">
			<van-button block type="primary" @click="handleSubmit" :loading="submitting">提交</van-button>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { normalizeDateTime, isEndAfterOrEqual } from '@/utils/timeUtils'
import FormItemRadio from '@/components/form-item-radio'
import FormItemDateTime from '@/components/form-item-time/FormItemDateTime.vue'
import FormFileUpload from '@/components/form-file-upload'
import { addGraywaterCheck, getGraywaterDetail } from '@/api/facilityGraywater'

const userStore = useUserStore()
const route = useRoute()
const isView = ref(route.query.isView === 'true')
function generateId() {
	return 'ID' + Math.random().toString(16).slice(2)
}
const form = reactive({
	id: generateId(), // 与废气/废水格式统一，用作业务主键与附件关联
	state: '1',
	exceptionType: '',
	exceptionDesc: '',
	beginTime: dayjs().format('YYYY-MM-DD HH:mm:00'),
	endTime: dayjs().format('YYYY-MM-DD HH:mm:00'),
	inflow: '',
	produce: '',
	bottom: '',
	fileData: [],
	businessId: 'GW_' + Date.now() + '_' + Math.random().toString(16).slice(2), // 兼容旧命名，如后端需要可同时传
	pollutionSourceId: '',
})

const minDate = dayjs().subtract(2, 'hour').toDate()
const maxDate = dayjs().add(30, 'day').toDate()

const loadDetail = async (id) => {
	if (!id) return
	try {
		const res = await getGraywaterDetail(id)
		if (res?.data) {
			Object.assign(form, res.data)
		}
	} catch (e) {}
}

const validate = () => {
	if (!form.beginTime || !form.endTime) return showToast('请选择时间'), false
	if (!isEndAfterOrEqual(form.beginTime, form.endTime)) return showToast('结束时间不能早于开始时间'), false
	if (form.state === '0') {
		if (!form.exceptionType) return showToast('请选择异常类型'), false
		if (!form.exceptionDesc) return showToast('请输入异常描述'), false
	}
	return true
}

const submitting = ref(false)
const handleSubmit = async () => {
	if (submitting.value) return
	if (!validate()) return
	if (!form.pollutionSourceId) return showToast('企业污染源ID缺失，无法提交'), false
	submitting.value = true
	try {
		const payload = {
			// 明确传递业务主键与兼容 businessId
			id: form.id,
			businessId: form.businessId,
			state: form.state,
			exceptionType: form.exceptionType,
			exceptionDesc: form.exceptionDesc,
			inflow: form.inflow,
			produce: form.produce,
			bottom: form.bottom,
			pollutionSourceId: form.pollutionSourceId,
			fileData: form.fileData.map((f) => ({ id: f.id, url: f.url, name: f.name })),
			beginTime: normalizeDateTime(form.beginTime),
			endTime: normalizeDateTime(form.endTime),
		}
		await addGraywaterCheck(payload)
		showToast('提交成功')
	} catch (e) {
		showToast(e?.message || '提交失败')
	} finally {
		submitting.value = false
	}
}

// 初始化（支持查看模式）
const init = async () => {
	let psId = userStore.userInfo?.omDepts?.id
	if (!psId) {
		try {
			const user = await userStore.ensureLogin()
			psId = user?.omDepts?.id
		} catch (e) {
			console.error('自动登录获取污染源ID失败', e)
		}
	}
	form.pollutionSourceId = psId || ''
	if (!form.pollutionSourceId) console.warn('污染源ID未获取到，将导致提交缺失必填字段')
	if (isView.value && route.query.id) {
		await loadDetail(route.query.id)
	}
}
onMounted(() => init())
</script>

<style lang="less" scoped>
.graywater-check-page {
	padding-bottom: 40px;
}
.page-title {
	font-size: 18px;
	font-weight: 600;
	padding: 16px;
}
.title-panel {
	font-weight: 600;
	margin: 8px 0 8px 12px;
}
.main-form {
	background: #fff;
	padding: 4px 8px 12px;
}
</style>
